use chrono::{DateTime, Local};
use crate::db::dao::im_message_dao::{message_inserts, message_send_total, message_total, message_updates, query_message_by_server_id, query_message_by_server_ids, query_messages, query_messages_by_session_id};
use crate::db::dao::im_message_send_dao::{change_message_send_action_status, message_send_query_by_user_id};
use crate::db::db::Db;
use crate::db::db_transaction::transaction;
use crate::db::pojo::pojo::{ImMessage, ImMessageActionData, ImMessageSend};

pub struct ImMessageService;

impl ImMessageService {

    pub fn inserts(&self, db: Db, messages: &mut Vec<ImMessage>) {
        if messages.is_empty() { return; }
        let mut message_list = messages.iter_mut().collect::<Vec<&mut ImMessage>>();
        message_inserts(db.clone(), &mut message_list);
    }

    pub fn updates(&self, db: Db, messages: &mut Vec<&mut ImMessage>) {
        if messages.is_empty() { return; }
        log::info!("message updates size: {}", messages.len());
        message_updates(db.clone(), messages);
    }

    pub fn total(&self) -> usize {
        let db = Db::open();
        let total = transaction(db.clone(), move |db: Db| {
            message_total(db)
        });
        total
    }

    pub fn message_send_total(&self) -> usize {
        let db = Db::open();
        let total = transaction(db.clone(), move |db: Db| {
            message_send_total(db)
        });
        total
    }

    pub fn query_message_by_server_id(user_id: &str, server_id: &str)->Option<ImMessage> {
        let db = Db::open();
        query_message_by_server_id(db.clone(), user_id, server_id)
    }

    pub fn query_message_by_server_ids(&self, user_id: &String, server_id_list: Vec<&str>)->Vec<ImMessage> {
        let db = Db::open();
        query_message_by_server_ids(db.clone(), user_id, server_id_list)
    }

    pub fn query_message_send_by_user_id(&self, message_id: u64, user_id: &String)->Option<ImMessageSend> {
        let db = Db::open();
        message_send_query_by_user_id(db.clone(), message_id, user_id.clone())
    }

    pub fn query_messages_by_session_id(&self, session_id: u64, server_date_time: Option<DateTime<Local>>, size: usize)->Vec<ImMessage> {
        let db = Db::open();
        query_messages_by_session_id(db.clone(), session_id, server_date_time, size)
    }

    pub fn query_messages(&self, size: usize)->Vec<ImMessage> {
        let db = Db::open();
        query_messages(db.clone(), size)
    }

    pub fn update_message_sends(&self, message_action_data_list: Vec<ImMessageActionData>) {
        let db = Db::open();
        change_message_send_action_status(db.clone(), message_action_data_list)
    }
}
